<?php

namespace App\Model\Dao;

use App\Concern\BaseDao;
use App\Utils\CustomUtils;
use Hyperf\Database\ConnectionInterface;
use Hyperf\Database\Query\Builder;
use Hyperf\DbConnection\Db;
use Hyperf\Utils\Arr;

/**
 * StatDailyTradeDao
 */
class StatDailyTradeDao extends BaseDao {

    /**
     * 表名常量
     * 联表的时候通过XxxDao::TABLE获取
     */
    const TABLE = "stat_daily_trade";

    // 不支持软删除
    protected $softDelete = 'delFlag';

    /**
     * 父类中通过静态函数获取表名, 因为不能通过静态常量获取, 这个函数是固定写在子类中的
     */
    public static function table (): string {
        return self::TABLE;
    }

    protected function _buildConnectionTable() : ConnectionInterface{
        return Db::connection('stat');
    }

    public function getStatCount ($param) {
        return $this->_buildQueryString($param)->count();
    }

    public function getStatList ($param, $page = null, $limit = null) {
        $builder = $this->_buildQueryString($param);
        $builder = $this->_buildQueryStatMchField($builder);
        $builder = $this->_buildOrder($builder, $param);
        $builder = $this->_buildPageLimit($builder, $page, $limit);
        return $builder->get()->toArray();
    }

    public function getFinanceList ($param, $page = null, $limit = null) {
        $builder = $this->_buildQueryString($param);
        $builder = $this->_buildQueryFinanceMchField($builder);
        $builder = $this->_buildOrder($builder, $param);
        $builder = $this->_buildPageLimit($builder, $page, $limit);
        return $builder->get()->toArray();
    }

    private function _buildQueryStatMchField(Builder $builder) {
        $builder->selectRaw(join(',', [
            "main.statMonth",
            "main.mchNo",
            "main.mchName",
            "main.settleCurrency",
            "main.successSettleAmount",
            "main.successCount",
            "main.totalCount",
            "main.refundCount",
            "main.disCount",
            "main.riskCount",
            "main.successRate",
            "main.disRate",
            "main.refundRate",
        ]));
        return $builder;
    }

    private function _buildQueryFinanceMchField(Builder $builder) {
        $builder->selectRaw(join(',', [
            "main.statMonth",
            "main.mchId",
            "main.mchNo",
            "main.mchName",
            "main.settleCurrency",
            "main.settleAmount",
            "main.successSettleAmount",
            "main.bondAmount",
            "main.thawSettleAmount",
            "main.frozenSettleAmount",
            "main.disSettleAmount",
            "main.refundSettleAmount",
            "main.serviceFee",
            "main.perFee",
            "main.refundFee",
            "main.disFee",
            "main.disLookIntoFee",
            "main.transFailFee",
            "main.threeDJudgeFee",
            "main.threeDFee",
            "main.salesCommission1",
            "main.salesCommission2",

            "trans.withdrawFee",
            "trans.transFee",

            "event.eventThawAmount",
            "event.eventDeductionAmount",
            "event.eventFreezeAmount",
            "event.eventRechargeAmount",
        ]));
        return $builder;
    }



    /**
     * 排序
     * @param Builder $builder
     * @param array   $params
     * @return Builder|mixed
     */
    protected function _buildOrder (Builder $builder, $params = []) {

        // 通过前端提交的参数排序
        if (Arr::exists($params, "orderBy")) {
            [$prop, $order] = $params["orderBy"];
            if (in_array($order, ["asc", "desc"])) {
                //switch ($prop) {
                //    case "yieldMonth":
                //        $builder->orderBy("main.yieldMonth", $order);
                //        break;
                //    default:
                //        break;
                //}
            }
        }

        // 如果友其他固定的排序需求, 在这里写, 例如按照时间降序
        $builder->orderBy("main.createTime", "desc");

        // 追加父类的排序, 父类按照ID升序, 保证排序结果唯一
        return parent::_buildOrder($builder, $params);
    }

    /**
     * 查询条件
     * @param $params
     * @return Builder
     */
    protected function _buildQueryString ($params) {
        // 本表一律命名为main
        $main = sprintf("%s AS main", self::TABLE);
        // $event = sprintf("%s AS event", StatMonthlyEventDao::TABLE);
        // $trans = sprintf("%s AS trans", StatMonthlyTransDao::TABLE);

        // 联表表明获取
        $builder = $this->_buildConnectionTable()->table($main);
                // ->leftJoin($event, "main.mchId", "=", "event.mchId")
                // ->leftJoin($trans, "main.mchId", "=", "trans.mchId");

        CustomUtils::xzxDebug($params);
        // 通过 Arr::exists 来判断是否存在该键, isset不准确
        (Arr::exists($params, "mchIdList") && !empty($params["mchIdList"])) && $builder->whereIn("main.mchId", $params['mchIdList']);
        (Arr::exists($params, "mchId") && $params["mchId"] !== "") && $builder->where("main.mchId", $params['mchId']);
        (Arr::exists($params, "mchNo") && !empty($params["mchNo"])) && $builder->where("main.mchNo", "like", "%{$params['mchNo']}%");
        (Arr::exists($params, "channelNo") && !empty($params["channelNo"])) && $builder->where("main.channelNo", "like", "%{$params['channelNo']}%");
        (Arr::exists($params, "channelName") && !empty($params["channelName"])) && $builder->where("main.channelName", "like", "%{$params['channelName']}%");
        Arr::exists($params, "statDate")  && $builder->whereBetween("main.statDate", $params['StatsTimeRange']);

        // $builder->whereRaw("main.statMonth = event.statMonth");
        // $builder->whereRaw("main.statMonth = trans.statMonth");
        $builder->where("main.delFlag", 0);
        // $builder->where("event.delFlag", 0);
        // $builder->where("trans.delFlag", 0);
        return $builder;
    }

    
}
